﻿using System;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Eneta.Portal.Common;
using Eneta.Portal.Common.Dto;
using Eneta.Portal.Common.Repository;
using Microsoft.SharePoint;
using Eneta.Portal.Common.Helpers;

namespace Eneta.Portal.Profiles.Controls
{
    public class ProfileLeftMenuControl : UserControl
    {
        protected HtmlGenericControl _titleContainer;
        protected HtmlAnchor _titleLink;
        protected HtmlGenericControl _profileContainer;

        protected HtmlAnchor _profileEditLink;
        protected HtmlImage _percentImage;
        protected HtmlGenericControl _profileIndicatorLabel;

        protected HtmlAnchor _yourCompaniesLink;
        protected HtmlGenericControl _companiesContainer;
        protected Repeater _companiesRepeater;

        protected HtmlAnchor _yourBlogsLink;
        protected HtmlGenericControl _blogsContainer;
        protected Repeater _blogsRepeater;

        protected HtmlAnchor _yourBooksLink;
        protected HtmlGenericControl _booksContainer;
        protected Repeater _booksRepeater;

        protected HtmlAnchor _yourAnnouncementsLink;
        protected HtmlGenericControl _announcementContainer;
        protected Repeater _announcementRepeater;

        protected HtmlAnchor _yourMagazinesLink;
        protected HtmlGenericControl _magazinesContainer;
        protected Repeater _magazinesRepeater;

        private CompanyRepository _companyRepository;
        private BlogRepository _blogRepository;
        private BookRepository _bookRepository;
        private NewsItemRepository _announcementRepository;
        private MagazineRepository _magazineRepository;

        private CompanyRepository CompanyRepository
        {
            get
            {
                if (_companyRepository != null)
                    return _companyRepository;

                _companyRepository = new CompanyRepository(EnetaApplication.PortalCompaniesSiteUrl);
                return _companyRepository;
            }
        }

        private BlogRepository BlogRepository
        {
            get
            {
                if (_blogRepository != null)
                    return _blogRepository;

                _blogRepository = new BlogRepository(EnetaApplication.PortalBlogSiteUrl);
                return _blogRepository;
            }
        }

        private BookRepository BookRepository
        {
            get
            {
                if (_bookRepository != null)
                    return _bookRepository;

                _bookRepository = new BookRepository(SPContext.Current.Web);
                return _bookRepository;
            }
        }

        private NewsItemRepository AnnouncementRepository
        {
            get
            {
                if (_announcementRepository != null)
                    return _announcementRepository;
                _announcementRepository = new NewsItemRepository(EnetaApplication.PortalNewsSiteUrl);
                return _announcementRepository;
            }
        }

        private MagazineRepository MagazineRepository
        {
            get
            {
                if (_magazineRepository != null)
                    return _magazineRepository;

                _magazineRepository = new MagazineRepository(SPContext.Current.Web);
                return _magazineRepository;
            }
        }

        private UserProfileDto _currentUserProfle;

        private UserProfileDto CurrentUserProfile
        {
            get
            {
                if (_currentUserProfle != null)
                    return _currentUserProfle;

                if (SPContext.Current.Web.CurrentUser == null)
                    return null;

                var profileRepository = new UserProfileRepository(SPContext.Current.Web);
                var user = SPContext.Current.Web.CurrentUser;
                _currentUserProfle = profileRepository.GetUserProfileByProfileName(user.Name); //SPContext.Current.Web.CurrentUser.GetUserProfile();
                return _currentUserProfle;
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            _blogsRepeater.ItemDataBound += BlogsRepeaterItemDataBound;
            _companiesRepeater.ItemDataBound += CompaniesRepeaterItemDataBound;
            _booksRepeater.ItemDataBound += BooksRepeaterItemDataBound;
            _announcementRepeater.ItemDataBound += AnnouncementRepeaterItemDataBound;
            _magazinesRepeater.ItemDataBound += MagazinesRepeaterItemDataBound;
        }

        protected void MagazinesRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            if (CurrentUserProfile == null)
                return;

            var magazine = (LiteratureDto)e.Item.DataItem;

            var magazineLink = (HtmlAnchor)e.Item.FindControl("_magazineLink");
            magazineLink.HRef = magazine.ItemUrl;
            magazineLink.InnerText = magazine.Title;
        }

        private void AnnouncementRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            if (CurrentUserProfile == null)
                return;

            var announcement = (AnnouncementDto)e.Item.DataItem;

            var announcementLink = (HtmlAnchor)e.Item.FindControl("_announcementLink");
            announcementLink.HRef = announcement.DisplayUrl;
            announcementLink.InnerText = announcement.Title;
            switch (announcement.Status)
            {
                case SPModerationStatusType.Approved:
                    announcementLink.InnerText += " - " + Resources.GetResourceString("Approved");
                    break;
                case SPModerationStatusType.Pending:
                    announcementLink.InnerText += " - " + Resources.GetResourceString("Pending");
                    break;
                case SPModerationStatusType.Denied:
                    announcementLink.InnerText += " - " + Resources.GetResourceString("Denied");
                    break;
            }
        }

        void BooksRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
           if (e.Item.DataItem == null)
                return;

            if (CurrentUserProfile == null)
                return;

            var book = (LiteratureDto)e.Item.DataItem;

            var bookLink = (HtmlAnchor)e.Item.FindControl("_bookLink");
            bookLink.HRef = book.ItemUrl;
            bookLink.InnerText = book.Title;
        }

        protected void BlogsRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            if (CurrentUserProfile == null)
                return;

            var blog = (BlogDto)e.Item.DataItem;

            var blogLink = (HtmlAnchor)e.Item.FindControl("_blogLink");
            blogLink.HRef = EnetaApplication.PortalProfilePageUrl + "?profileID=" + CurrentUserProfile.Id + "#b" + blog.ID;
            blogLink.InnerText = blog.Title;
        }

        protected void CompaniesRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            if(CurrentUserProfile == null)
                return;

            var company = (CompanyDto)e.Item.DataItem;
            
            var companyLink = (HtmlAnchor) e.Item.FindControl("_companyLink");
            companyLink.HRef = "/profile.aspx?ID=" + CurrentUserProfile.Id + "#c" + company.Id;
            companyLink.InnerText = company.Title;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            var currentUser = SPContext.Current.Web.CurrentUser;

            HideControls();

            if (currentUser == null)
            {
                Logger.LogInfo("OnLoad(): Current user is null");
                return;
            }
            if (CurrentUserProfile == null)
            {
                Logger.LogInfo("OnLoad(): Current user has no profile");
                return;
            }
            _titleLink.HRef = EnetaApplication.PortalProfilePageUrl + "?profileID=" + CurrentUserProfile.Id;
            _titleContainer.Visible = true;
            _profileEditLink.HRef = EnetaApplication.PortalProfileEditPageUrl + "?profileID=" + CurrentUserProfile.Id;
            _profileEditLink.Visible = true;
            _profileContainer.Visible = true;

            var indicatorValue = CurrentUserProfile.GetProfileFillmentPercent();
            _profileIndicatorLabel.InnerText = Resources.GetResourceString("ProfilePercentagePrefix") + " " + indicatorValue + "% " + Resources.GetResourceString("ProfilePercentageSuffix");
            _percentImage.Style["width"] = indicatorValue + "%";
            _percentImage.Alt = _profileIndicatorLabel.InnerText;

            try
            {
                var companies = CompanyRepository.GetUserCompanies(currentUser.ID, false);
                _yourCompaniesLink.HRef = EnetaApplication.PortalProfilePageUrl + "?profileID=" + CurrentUserProfile.Id + "#firmad";
                _companiesRepeater.DataSource = companies;
                _companiesRepeater.DataBind();
                _companiesContainer.Visible = true;
            }
            catch (Exception ex)
            {
                var message = "Error binding companies";
                var appEx = new ApplicationException(message, ex);
                Logger.LogException(appEx);
            }

            try
            {
                var blogs = BlogRepository.GetUserBlogs(currentUser.ID);
                _yourBlogsLink.HRef = EnetaApplication.PortalProfilePageUrl + "?profileID=" + CurrentUserProfile.Id + "#blogid";
                _blogsRepeater.DataSource = blogs;
                _blogsRepeater.DataBind();
                _blogsContainer.Visible = true;
            }
            catch (Exception ex)
            {
                var message = "Error binding blogs";
                var appEx = new ApplicationException(message, ex);
                Logger.LogException(appEx);            
            }
            try
            {
                var books = BookRepository.GetUserBooks(currentUser.ID);
                _yourBooksLink.HRef = UrlHelper.GetProfileUrl(CurrentUserProfile.Id) + "#raamatud";
                _booksRepeater.DataSource = books;
                _booksRepeater.DataBind();
                _booksContainer.Visible = true;
            }
            catch(Exception ex)
            {
                var message = "Error binding books";
                var appEx = new ApplicationException(message, ex);
                Logger.LogException(appEx);
            }

            try
            {
                var announcements = AnnouncementRepository.GetUserAnnouncements(currentUser.ID, 5);
                _yourAnnouncementsLink.HRef = EnetaApplication.PortalProfilePageUrl + "?profileID=" + CurrentUserProfile.Id + "#teated";
                _announcementRepeater.DataSource = announcements;
                _announcementRepeater.DataBind();
                _announcementContainer.Visible = true;
            }
            catch (Exception ex)
            {
                var message = "Error binding announcements";
                var appEx = new ApplicationException(message, ex);
                Logger.LogException(appEx);
            }
            try
            {
                var magazines = MagazineRepository.GetUserMagazines(currentUser.ID);
                _yourMagazinesLink.HRef = UrlHelper.GetProfileUrl(CurrentUserProfile.Id) + "#ajakirjad";
                _magazinesRepeater.DataSource = magazines;
                _magazinesRepeater.DataBind();
                _magazinesContainer.Visible = true;
            }
            catch (Exception ex)
            {
                var message = "Error binding magazines";
                var appEx = new ApplicationException(message, ex);
                Logger.LogException(appEx);
            }
        }        

        private void HideControls()
        {
            _titleContainer.Visible = false;
            _profileContainer.Visible = false;
            _profileEditLink.Visible = false;
            _companiesContainer.Visible = false;
            _blogsContainer.Visible = false;
            _booksContainer.Visible = false;
            _announcementContainer.Visible = false;
            _magazinesContainer.Visible = false;
        }
    }
}